package com.first.community.controller;

import com.first.community.dto.AccessTokenDTO;
import com.first.community.dto.GithubUser;
import com.first.community.mapper.UserMapper;
import com.first.community.model.User;
import com.first.community.model.UserExample;
import com.first.community.provider.GithubProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.UUID;

@Controller
public class AuthorizeController {

    @Autowired
    private GithubProvider githubProvider;

    @Autowired
    private UserMapper userMapper;

    @Value("${github.client.id}")
    private String Client_id;

    @Value("${github.client.secret}")
    private  String Client_secrect;

    @Value("${github.redirect.uri}")
    private  String Redirect_uri;


    @GetMapping("/callback")
    public String getCode(@RequestParam(name="code") String code,
                          @RequestParam(name="state") String state,
                          HttpServletResponse response){
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        accessTokenDTO.setClient_id(Client_id);
        accessTokenDTO.setClient_secret(Client_secrect);
        accessTokenDTO.setCode(code);
        accessTokenDTO.setRedirect_uri(Redirect_uri);
        accessTokenDTO.setState(state);
        String accessToken = githubProvider.getAccessToken(accessTokenDTO);
        GithubUser githubUser = githubProvider.getUser(accessToken);
        if(githubUser!=null){
            //登陆成功

            //判断数据库中是否已经有该用户
            UserExample example = new UserExample();
            example.createCriteria()
                    .andAccountIdEqualTo(githubUser.getId());
            User user = null;
            List<User> users = userMapper.selectByExample(example);

            if(users.size()!=0){
                //更新用户信息
                User dbUser = users.get(0);
                user = dbUser;
                dbUser.setBio(githubUser.getBio());
                dbUser.setAvatarUrl(githubUser.getAvatar_Url());
                dbUser.setGmtModified(System.currentTimeMillis());
                dbUser.setName(githubUser.getName());
                UserExample userExample = new UserExample();
                userExample.createCriteria()
                        .andAccountIdEqualTo(githubUser.getId());
                userMapper.updateByExampleSelective(dbUser,userExample);
            }else{
                //插入数据库
                user = new User();
                user.setAccountId(githubUser.getId());
                user.setName(githubUser.getName());
                user.setToken(UUID.randomUUID().toString());
                user.setGmtCreate(System.currentTimeMillis());
                user.setGmtCreate(user.getGmtCreate());
                user.setBio(githubUser.getBio());
                user.setAvatarUrl(githubUser.getAvatar_Url());
                userMapper.insert(user);
            }
         

            //写入Cookie
            response.addCookie(new Cookie("token",user.getToken()));

            return "redirect:/";
        }else{
            //登陆失败
            return "redirect:/";
        }
    }
}
